<template>
  <div class="main-content">
    <div style="width: 90%; background-color: white; margin: 30px auto; border-radius: 20px">
      <div style="padding-bottom: 10px">
        <div style="display: flex; font-size: 18px; color: #000000FF; line-height: 80px; border-bottom: #cccccc 1px solid; justify-content: space-between; align-items: center;">
          <div style="flex: 1; text-align: center;">全部商品（{{ cartItems.length }} 件）</div>
          <div style="flex: 2; text-align: right">
            <el-select v-model="selectedAddress" placeholder="请选择收货地址" style="width: 70%">
              <el-option v-for="address in cartItems" :key="address.userAddress" :label="address.userAddress" :value="address.id"></el-option>
            </el-select>
          </div>
          <div style="flex: 1; font-size: 16px; text-align: right; padding-right: 20px">
            已选商品 ￥ {{ totalAmount }} <el-button type="danger" round @click="placeOrder">下单</el-button>
          </div>
        </div>
        <div style="margin: 20px 0; padding: 0 50px">
          <div class="table" v-if="cartItems && cartItems.length > 0">
            <el-table :data="cartItems" stripe @selection-change="handleSelectionChange" style="font-size: 18px;">
              <el-table-column type="selection" width="60px"></el-table-column>
              <el-table-column label="商品图片" width="200px" height="120px">
                <template #default="scope">
                  <el-image style="width: 100px; height: 100px; border-radius: 3px" v-if="scope.row.goodsPhoto" :src="scope.row.goodsPhoto"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称" width="250px">
                <template #default="scope">
                  <a :href="'/user/store/detail?id=' + scope.row.goodsId" style="text-decoration: none; font-size: 18px;">{{ scope.row.goodsName }}</a>
                </template>
              </el-table-column>
              <el-table-column label="商品价格">
                <template #default="scope"> 
                  {{ scope.row.goodsPrice }} 元
                </template>
              </el-table-column>
              <el-table-column prop="goodsnumber" label="选择数量" width="200px">
                <template #default="scope">
                  <el-input-number v-model="scope.row.goodsnumber" style="width: 100px; font-size: 18px;" @change="updateQuantity(scope.row)" :min="1"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="小计" width="100px">
                <template #default="scope">
                  <span style="color: #FF6700;">{{ calculateSubtotal(scope.row) }}元</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180">
                <template #default="scope">
                  <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)" style="font-size: 16px;" circle>×</el-button>                
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="margin-top: 20px">
              <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20]"
                :page-size="pageSize"
                layout=" prev, pager, next"
                :total="total">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CartListService, updateCartService, deleteCartService, addOrderService } from '@/api/cart.js';

export default {
  setup() {
    const cartItems = ref([]);
    const selectedItems = ref([]);
    const selectedAddress = ref('');
    const addresses = ref([]);
    const pageNum = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    const totalAmount = computed(() => {
      return cartItems.value
        .filter(item => selectedItems.value.includes(item.id))
        .reduce((total, item) => total + item.goodsPrice * item.goodsnumber, 0);
    });

    const fetchCartItems = async () => {
      try {
        const params = {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
        };
        const response = await CartListService(params);
        cartItems.value = response.data.list;
        total.value = response.data.total;
      } catch (error) {
        console.error('获取购物车列表失败:', error);
      }
    };

    const updateQuantity = async (item) => {
      try {
        await updateCartService({ id: item.id, goodsnumber: item.goodsnumber });
      } catch (error) {
        console.error('更新购物车数量失败:', error);
      }
    };

    const handleDelete = (id) => {
      ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteCartService(id);
          ElMessage.success('删除成功');
          fetchCartItems();
        } catch (error) {
          ElMessage.error('删除失败');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    };

    const placeOrder = () => {
      if (!selectedAddress.value) {
        ElMessage.info('请选择收货地址');
        return;
      }
      if (selectedItems.value.length === 0) {
        ElMessage.info('请选择商品');
        return;
      }
      // 处理下单逻辑
      let data = {
        cartData: cartItems.value.filter(item => selectedItems.value.includes(item.id)).map(row => ({
          id: row.id,
          goodsId: row.goodsId,
          userAddress: selectedAddress.value,
          goodsnumber: row.goodsnumber,
          goodsPhoto: row.goodsPhoto,
          goodsName: row.goodsName,
          goodsPrice: row.goodsPrice
        }))
      }
      addOrderService(data).then(res => {
        ElMessage.success('下单成功')
      }).catch(err => {
        ElMessage.error('下单失败')
      })
    };

    const handleSelectionChange = (rows) => {
      selectedItems.value = rows.map(row => row.id);
    };

    const handleCurrentChange = (newPageNum) => {
      pageNum.value = newPageNum;
      fetchCartItems();
    };

    const calculateSubtotal = (item) => {
      return item.goodsPrice * item.goodsnumber;
    };

    onMounted(() => {
      fetchCartItems();
    });

    return {
      cartItems,
      selectedItems,
      selectedAddress,
      addresses,
      totalAmount,
      updateQuantity,
      handleDelete,
      placeOrder,
      handleSelectionChange,
      handleCurrentChange,
      pageNum,
      pageSize,
      total,
      calculateSubtotal,
    };
  }
};
</script>